package com.surelution.projects.crm

import java.awt.image.BufferedImage;
import java.text.SimpleDateFormat

import javax.imageio.ImageIO;
import javax.imageio.ImageReader
import javax.imageio.stream.ImageInputStream

class ImportExcelService {

    static transactional = true
	
	def grailsApplication

    def storeFile(InputStream stream,String fileName) {
		def file = new ImportExcel()
		file.importTime = new Date()

		def baseDir = grailsApplication.config.binaryFile.importFile.baseDir
		def sdf = new SimpleDateFormat("yyyy/MM/dd/")
		def guid = UUID.randomUUID().toString()
		file.filePath = sdf.format(file.importTime)
		file.fileName = fileName
		file.name = guid
		
		String path = baseDir + file.filePath

		File dir = new File(path)
		if(!dir.exists()) {
			dir.mkdirs()
		}
		
		File f = new File(dir, file.name)
		
		FileOutputStream fos = new FileOutputStream(f)
		fos << stream
		fos.close()
		
		stream.close()
		return file
    }

	def loadFile(ImportExcel file) {
		def baseDir = grailsApplication.config.binaryFile.importFile.baseDir
		def path = baseDir + file.filePath
		return path + file.name
	}
	
	def deleteFile(ImportExcel file) {
		def filePath = loadFile(file)
		def f = new File(filePath)
		f.delete()

		if(file.exists())
			file.delete()
		return true
	}
}
